#include "../../../vcd-common-api/vcd-common.h"
#include "../../vcd-message-dialog.h"
#include "vcd-diagnosis.h"

typedef struct
{
    GtkWidget *buffer_label;
    GtkWidget *entry_IP;
    GtkWidget *btn_internet_conn;
    GtkWidget *check_btn1;
    GtkWidget *check_btn2;
} ping;
ping text;

static GThread *g_ping_thread = NULL;

volatile gint g_flag_ping = 0;

GtkWidget *get_ping_setting_fix(void);

void ping_checkbtn1_toggled(GtkCheckButton *checkbtn);
void ping_checkbtn2_toggled(GtkCheckButton *checkbtn);
void btnIntConnstop(void);
gboolean deal_with_ping(void);//多线程解决
void btnIntConn(void);
void ping_check_btn2_toggled(GtkCheckButton *check_btn);
void ping_check_btn1_toggled(GtkCheckButton *check_btn);

GtkWidget* get_setting_diagnosis(void)
{
    GtkWidget *grid_diagnosis= gtk_grid_new();
    GtkWidget *ipfixed = get_ping_setting_fix();

    gtk_grid_attach((GtkGrid *)grid_diagnosis, ipfixed, 0, 0, 1, 1);
    return grid_diagnosis;
}


void ping_check_btn1_toggled(GtkCheckButton *check_btn)
{
    gboolean bres = gtk_toggle_button_get_active((GtkToggleButton *)check_btn);
    gtk_toggle_button_set_active((GtkToggleButton *)text.check_btn2, !bres);
    g_atomic_int_set(&g_flag_ping, 0);
}

void ping_check_btn2_toggled(GtkCheckButton *check_btn)
{
    gboolean bres = gtk_toggle_button_get_active((GtkToggleButton *)check_btn);
    gtk_toggle_button_set_active((GtkToggleButton *)text.check_btn1, !bres);
    g_atomic_int_set(&g_flag_ping, 0);

}


gboolean deal_with_ping(void)//多线程解决
{
    int buf_length = 100;
    const gchar *IP = gtk_entry_get_text(GTK_ENTRY(text.entry_IP));

    FILE *pf;
    char cmd[buf_length + 20];
    gboolean continued = gtk_toggle_button_get_active((GtkToggleButton *)text.check_btn1);
    if (continued){
        snprintf(cmd, sizeof(cmd),"ping -W 1 %s", IP);
    } else{
        snprintf(cmd, sizeof(cmd), "ping -c 4 -W 1 %s", IP);
    }

    char buff[4096] = {0};
    pf = popen(cmd, "r");

    GSList* resp = NULL;
    gint recv_len = 1024;

    while (g_atomic_int_get(&g_flag_ping) != 0)
    {
        gpointer d = g_malloc0(recv_len + 2);
        char* p = fgets((char*)d, recv_len, pf);
        if(p == NULL){
            g_free(d);
            d = NULL;
            break;
        }

        //limit 5 lines
        resp = g_slist_append(resp, d);
        guint count = g_slist_length(resp);
        if(count > 50){
            //pop front
            gpointer first = g_slist_nth_data(resp, 0);
            resp = g_slist_remove(resp, first);
            if(first){
                g_free(first);
                first = NULL;
            }
        }

        //show response
        gint i = 0;
        int pos = 0;
        for(; i < count; ++i){
            gpointer* f = g_slist_nth_data(resp, i);
            if(f == NULL){
                break;
            }
            int len = snprintf(buff + pos, sizeof(buff) - pos, "%s", (char*)f);
            if(len <= 0){
                break;
            }
            pos += len;
        }

        gdk_threads_enter();
        gtk_label_set_text((GtkLabel *)text.buffer_label, buff);
        gdk_threads_leave();
    }
    pclose(pf);

    //free alloc
    while(g_slist_length(resp) > 0){
        gpointer first = g_slist_nth_data(resp, 0);
        resp = g_slist_remove(resp, first);
        if(first){
            g_free(first);
            first = NULL;
        }
    }
    return FALSE;
}

void btnIntConn(void)
{
    const gchar *ip = gtk_entry_get_text(GTK_ENTRY(text.entry_IP));
    if (ip == NULL || strlen(ip) == 0) {
        message_box("请输入参数");
        return;
    }

    //stop first
    btnIntConnstop();

    g_atomic_int_set(&g_flag_ping, 1);

    M_DEBUG("start thread\n");
    gtk_label_set_text((GtkLabel *)text.buffer_label, "nowing ping...\n");
    gtk_label_set_yalign((GtkLabel *)text.buffer_label, 0.00);
    gtk_label_set_xalign((GtkLabel *)text.buffer_label, 0.00);

    GThread *thd = g_thread_new("deal_ping", (GThreadFunc)deal_with_ping, NULL);
    if(thd == NULL){
        return;
    }

    g_ping_thread = thd;

    //      gdk_threads_add_idle(deal_with_ping,NULL);
    //      g_main_context_invoke(NULL,(GSourceFunc)deal_with_ping(),NULL);
    //      g_idle_add((GSourceFunc)deal_with_ping(),NULL);

}

void btnIntConnstop(void)
{
    if(g_atomic_int_get(&g_flag_ping) == 0){
        return;
    }

    g_atomic_int_set(&g_flag_ping, 0);
    if(g_ping_thread){
        system("killall ping");
        g_thread_join(g_ping_thread);
        g_ping_thread = NULL;
    }

    char buff[2048] = {0};
    gtk_label_set_yalign((GtkLabel *)text.buffer_label, 0.00);
    gtk_label_set_xalign((GtkLabel *)text.buffer_label, 0.00);

    const char* p = gtk_label_get_text((GtkLabel *)text.buffer_label);
    snprintf(buff, sizeof(buff),"%s已取消...", p);

    gtk_label_set_text((GtkLabel *)text.buffer_label, buff);
}

void stop_ping(void)
{
    btnIntConnstop();
}

GtkWidget *get_ping_setting_fix(void)
{
    GtkWidget *ip_fixed = gtk_fixed_new();

    GtkWidget *label_Please_info = gtk_label_new("        请输入需要ping的网络地址           ");
    gtk_widget_set_size_request(label_Please_info, 210, 20.5);
    set_img(label_Please_info, "label", "ping.png");
    //gtk_widget_set_can_focus(label_Please_info, TRUE);
    //gtk_widget_grab_focus(label_Please_info);

    text.entry_IP = gtk_entry_new();
    gtk_entry_set_max_length(GTK_ENTRY(text.entry_IP), 100);
    gtk_entry_set_placeholder_text(GTK_ENTRY(text.entry_IP), "例如:192.168.1.1或www.baidu.com");

    gtk_widget_set_size_request(text.entry_IP, 500, 35);
    set_css(text.entry_IP, "entry{border-radius:0px}");
    text.btn_internet_conn = gtk_button_new_with_label("ping");
    gtk_button_set_relief(GTK_BUTTON(text.btn_internet_conn), GTK_RELIEF_NONE);
    gtk_widget_set_size_request(text.btn_internet_conn, 70, 10);

    GtkWidget *btn_stop_ping = gtk_button_new_with_label("取消");
    gtk_button_set_relief(GTK_BUTTON(btn_stop_ping), GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_stop_ping, 70, 10);

    text.check_btn1 = gtk_check_button_new_with_label("持续发送ping包");
    text.check_btn2 = gtk_check_button_new_with_label("仅发送4个ping包");
    gtk_toggle_button_set_active ((GtkToggleButton *)text.check_btn1, FALSE);
    gtk_toggle_button_set_active ((GtkToggleButton *)text.check_btn2, TRUE);

    text.buffer_label = gtk_label_new(NULL);
    gtk_widget_set_size_request(text.buffer_label, 500, 190);
    gtk_label_set_max_width_chars((GtkLabel *)text.buffer_label, 50);
    gtk_label_set_line_wrap((GtkLabel *)text.buffer_label, TRUE);
    gtk_label_set_lines((GtkLabel *)text.buffer_label, 4);

    GtkWidget* scrolled_win = gtk_scrolled_window_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(scrolled_win), text.buffer_label);
    gtk_widget_set_size_request(scrolled_win, 500, 190);

    gtk_fixed_put((GtkFixed *)ip_fixed, label_Please_info,      40,  55);
    gtk_fixed_put((GtkFixed *)ip_fixed, text.entry_IP,         40,  88);
    gtk_fixed_put((GtkFixed *)ip_fixed, text.btn_internet_conn, 390, 165);
    gtk_fixed_put((GtkFixed *)ip_fixed, btn_stop_ping,        470, 165);
    gtk_fixed_put((GtkFixed *)ip_fixed, text.check_btn1,       40,  140);
    gtk_fixed_put((GtkFixed *)ip_fixed, text.check_btn2,       200, 140);
   // gtk_fixed_put((GtkFixed *)ip_fixed, text.buffer_label,    40,  220);
    gtk_fixed_put((GtkFixed *)ip_fixed, scrolled_win,    40,  220);

    g_signal_connect(G_OBJECT(text.check_btn1),      "toggled",       G_CALLBACK(ping_check_btn1_toggled), NULL);
    g_signal_connect(G_OBJECT(text.check_btn2),      "toggled",       G_CALLBACK(ping_check_btn2_toggled), NULL);
    g_signal_connect(G_OBJECT(text.btn_internet_conn), "clicked",       G_CALLBACK(btnIntConn),             NULL);
    g_signal_connect(G_OBJECT(btn_stop_ping),       "clicked",       G_CALLBACK(btnIntConnstop),         NULL);

    set_css(btn_stop_ping,     "button{ color:white;"
                               "background:#5cb85c;border: 1px solid rgb(57,132,57);"
                               "border-radius:0px}");
    set_css(btn_stop_ping,     "button:hover{border-radius:0px;background: #449d44;}");
    set_css(text.buffer_label, "label{ border-left:4px solid rgb(227,227,227);"
                               "border-top:1px solid rgb(227,227,227);"
                               "border-right:1px solid rgb(227,227,227);"
                               "border-bottom:1px solid rgb(227,227,227);"
                               "border-radius:0px;"
                               "background-color:rgb(248,248,248)}");
    set_css(text.btn_internet_conn, "button{ color:white;"
                                    "background:rgb(53,126,169);"
                                    "border:1px solid rgb(40,94,142);"
                                    "border-radius: 0px}");

    set_css(text.btn_internet_conn, "button:hover{border-radius:0px;background:#3070a9}");

    return ip_fixed;
}
